from fastapi import FastAPI, Query
from path import Path
from pydantic import BaseModel, field_validator
import uvicorn

"""
    晚上的作业：
    1. 课件中的代码，敲一遍
    2. 对学生管理系统提供API接口
        a. 查询所有学生的信息
        b. 根据学生编号查询某个学生的信息
        c. 添加学生信息
        d. 根据学生姓名查询学生的信息
    3. 根据学生编号更新学生的信息（可以后做）
    4. 根据昨天的沃林学生基本信息表和就业信息表，用昨天那个学生管理系统给他实现。
"""

app = FastAPI()
# 学生数据模型
class Student(BaseModel):
    student_id: int
    name: str
    email: str
    phone: str
    age: int
    class_name: str

    # 检查手机号必须是11位数字
    @field_validator('phone')
    def validate_phone(cls, v):
        if not v.isdigit() or len(v) != 11:
            raise ValueError('手机号必须是11位数字')
        return v

    # 检查邮箱必须包含@符号
    @field_validator('email')
    def validate_email(cls, v):
        if '@' not in v:
            raise ValueError('邮箱必须包含@符号')
        return v

    # 检查年龄必须在0-100岁之间
    @field_validator('age')
    def validate_age(cls, v):
        if not 0 < v < 100:
            raise ValueError('年龄必须在0到100岁之间')
        return v


# 模拟数据库
students_db = []

# 生成10个示例学生（Ai生成）
sample_data = [
    {"student_id": 1001, "name": "张三", "email": "zhangsan@qq.com", "phone": "13800138000", "age": 20,
     "class_name": "AI0804"},
    {"student_id": 1002, "name": "李四", "email": "lisi@163.com", "phone": "13900139000", "age": 21,
     "class_name": "AI0804"},
    {"student_id": 1003, "name": "王五", "email": "wangwu@gmail.com", "phone": "15000150000", "age": 22,
     "class_name": "AI0805"},
    {"student_id": 1004, "name": "赵六", "email": "zhaoliu@126.com", "phone": "15100151000", "age": 19,
     "class_name": "AI0805"},
    {"student_id": 1005, "name": "钱七", "email": "qianqi@qq.com", "phone": "15200152000", "age": 23,
     "class_name": "AI0804"},
    {"student_id": 1006, "name": "孙八", "email": "sunba@163.com", "phone": "15300153000", "age": 20,
     "class_name": "AI0806"},
    {"student_id": 1007, "name": "周九", "email": "zhoujiu@gmail.com", "phone": "15400154000", "age": 21,
     "class_name": "AI0806"},
    {"student_id": 1008, "name": "吴十", "email": "wushi@126.com", "phone": "15500155000", "age": 22,
     "class_name": "AI0804"},
    {"student_id": 1009, "name": "郑十一", "email": "zhengshiyi@qq.com", "phone": "15600156000", "age": 19,
     "class_name": "AI0805"},
    {"student_id": 1010, "name": "王十二", "email": "wangshier@163.com", "phone": "15700157000", "age": 24,
     "class_name": "AI0806"}
]

# 初始化数据
for data in sample_data:
    students_db.append(Student(**data))


# a. 查询所有学生的信息
@app.get("/students/list")
def get_all_students():
    return students_db


# b. 根据学生编号查询某个学生的信息
@app.get("/students/id/{student_id}")
def get_student_by_id(student_id: int):  # 改为int类型
    for student in students_db:
        if student.student_id == student_id:  # 改为student.student_id
            return student
    return {"message": "学生不存在", "student": None}


# c. 添加学生信息
@app.post("/students")
def add_student(student: Student):
    # 检查学生编号是否重复 ##这里可以直接get一个，而不是遍历一次
    for existing_student in students_db:
        if existing_student.student_id == student.student_id:
            return {"message": "学生编号已存在", "student": None}

    students_db.append(student)
    return {"message": "学生添加成功", "student": student}

# d. 根据学生姓名查询学生的信息
@app.get("/students/name/{student_name}")
def get_student_by_name(student_name: str):
    result = [student for student in students_db if student_name in student.name]
    if not result:
        return {"message": "未找到该姓名的学生", "students": None}
    return {"students": result}


if __name__ == '__main__':
    uvicorn.run('0411作业:app', host='localhost', port=8000, reload=True)

#请求体，初始化校验，依赖注入校验。

"""
get_stus?page=1&limit=20

@app.get("/items/path/{itemid}")
def parameter_path(
        *,
        itemid: int = Path(title='Item 编号', ge=100, le=2000),
        q: str,
        size: float = Query(default=None, le=50.0)
    ):
    resultsI {"itemlid": itemid}
    results.update({'q': q})
    if size:
    results.update({"size": size})
    return results
"""
